/**
 * 微信小程序支付
 * 此处针对于微信小程序开发的支付插件
 * 
 * @param {sn}
 */

import {
	initiatePay
} from "@/api/trade";

export const WXPaySdk = ({
	sn,
	orderType = 'TRADE',
	clientType = 'WECHAT_MP',
	paymentMethod = 'WECHAT',
	paymentClient = 'MP'
}) => {
	return new Promise((resolve, reject) => {

		uni.showLoading({
			title: "检测支付环境...",
		});

		let submitData = {
			sn,
			orderType,
			clientType,
		};


		initiatePay(paymentMethod, paymentClient, submitData).then((res) => {
			uni.hideLoading();
			if (res.data.success) {
				let response = res.data.result;
				uni.requestPayment({
					provider: "wxpay",
					appid: response.appid,
					timeStamp: response.timeStamp,
					nonceStr: response.nonceStr,
					package: response.package,
					signType: response.signType,
					paySign: response.paySign,
					success: (e) => {
						uni.showToast({
							icon: "none",
							title: "支付成功!",
						});
						resolve(true)
					},
					fail: (e) => {
						this.exception = e;
						// 支付异常或支付失败之后跳转到订单页面
						uni.showModal({
							content: "支付失败,如果您已支付，请勿反复支付",
							showCancel: false,
							success: () => {
								reject(false)
							},
						});
					},
				});
			} else {
				uni.showToast({
					icon: "none",
					title: "服务请求失败",
				});
				reject(false)
			}

		});

	})
}